<script lang='ts' setup>
import {reactive, ref} from 'vue'
import type {UploadProps, UploadUserFile, ElMessage} from 'element-plus'
import {useFile} from "@/hooks/web/useFile";

const {action, headers,showViewer,srcList, handlePreview} = useFile()
const props = defineProps({
  fileType: {default: 'picture'},
  fileAccept: {default: ''},
  fileStyle:{},
  limit:{default:1}
})

const fileList = ref<UploadUserFile[]>([])
const fileArr = ref([])
const handleRemove = (file, fileList) => {
  console.log(fileList);
  fileList.value = fileList
  fileArr.value = fileList
}

const upload = ref<UploadInstance>()

const handleExceed: UploadProps['onExceed'] = (files) => {
  ElMessage.warning(`文件限制最多只能上传 ${files.length}个`)
}

const beforeUpload =(file) =>{
  console.log(file, 'image')
  const isLt500KB = file.size / 1024 / 1024 < 0.5;
  if (!isLt500KB) {
    ElMessage.warning(`上传的文件大小不能超过 500KB!`)
  }
  return isLt500KB;
}

const handleSuccess = (response) => {
  if (response.code === 0) {
    fileArr.value.push({
      url: response.data.url,
      name: response.data.name,
      file_id:response.data.file_id
    })
    fileList.value =  fileArr.value
  }
}

defineExpose({fileList,fileArr})

</script>
<template>
  <el-upload
      v-model:file-list="fileList"
      :action="action"
      :on-preview="handlePreview"
      :headers="headers"
      :on-success="handleSuccess"
      :limit="props.limit"
      :before-upload="beforeUpload"
      ref="upload"
      :accept="props.fileAccept"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
      :list-type="props.fileType">
    <slot name="button">
      <el-button v-if="props.fileType !=='picture-card'" type="primary" slot="default">选取文件</el-button>
      <el-icon v-else>
        <Plus/>
      </el-icon>
    </slot>
  </el-upload>
  <el-image-viewer
      v-if="showViewer"
      :z-index="9999"
      @close="()=>{showViewer  =false}"
      :url-list="srcList"
  />
</template>
<style scoped>
.upload-demo {
  width: 200px;
}
</style>